package logic

import (
	"context"
	"fmt"
	"product/model/cache"
	"product/model/mysql"
	"product/pkg"

	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登陆
func (l *LoginLogic) Login(in *productrpc.LoginRequest) (*productrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("请前去注册,用户不存在")
	}
	if pkg.Md5(in.Password) == "" {
		if in.SendCode == "" {
			result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()

			if result != in.SendCode {
				return nil, fmt.Errorf("验证码错误请重新输入")
			}
		}
	} else {
		if finduser.Password != pkg.Md5(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	}

	return &productrpc.LoginResponse{
		Id: int64(finduser.ID),
	}, nil
}
